package assign4;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.Random;

/** A basic client for testing the functionality of an IRemoteDatabase
 * each client runs on a separate thread so that they can emulate the
 * concurrent behavior of multiple machine based clients.
 */
public class ReplicatedDBClient implements Runnable
{
	private String clientName;
	private String serverURL = Globals.serverNamePrefix;
	
	IRemoteDatabase server;
	
	public ReplicatedDBClient(String clientName, String serverName) throws Exception
	{
		super();
		Policy.init(ReplicatedDBClient.class);
		this.clientName = clientName;
		
		serverURL += serverName;
		server = (IRemoteDatabase) Naming.lookup(serverURL);
	}
	
	public void run()
	{
		while(true)
		{
			try
			{
				int value;
				Random randomGenerator = new Random();
				int tableToHit = randomGenerator.nextInt(Globals.numOfDatabaseTables);
				
				int rounds = Integer.parseInt("1");
				// System.out.println(clientName + " " + rounds + " rounds on " + serverURL);
				for (int i = 0; i < rounds; i++)
				{
					value = server.read(tableToHit);
					System.out.println(clientName + " reads: " + value +" from table: " + tableToHit);
					server.write(value + 1, tableToHit);
					System.out.println(clientName + " writes: " + (value+1) +" to table: " + tableToHit);
				}
				
    			try{Thread.sleep((long)(Math.random() * 3000) + 100);}
				catch (InterruptedException e){}
			}
			catch(RemoteException e)
			{
				e.printStackTrace();
			}
		}
	}
}
